// Copyright 2023 Srhino Co., Ltd. All rights reserved.

package discovery

type Discover struct {
	Rules               []*DiscoverRule
	DisableInternalRule bool
}

type DiscoverInterface interface {
	DiscoveryApi(req *ApiRequest) (bool, error)
	SetRules(rules []*DiscoverRule)
	GetDefaultRules() []*DiscoverRule
}

var _ DiscoverInterface = (*Discover)(nil)

func NewDiscover(rules []*DiscoverRule, disInternalRule bool) *Discover {
	return &Discover{
		Rules:               rules,
		DisableInternalRule: disInternalRule,
	}
}

func (d *Discover) DiscoveryApi(req *ApiRequest) (bool, error) {

	if len(d.Rules) == 0 && !d.DisableInternalRule {
		d.setDefaultRules()
	}

	for _, rule := range d.Rules {

		if rule.Match(req) {
			//fmt.Printf("%+v \n", rule)
			return true, nil
		}

	}

	return false, NotMatched
}

func (d *Discover) setDefaultRules() {
	d.Rules = DefaultRules
}

func (d *Discover) SetRules(rules []*DiscoverRule) {
	d.Rules = rules
}

func (d *Discover) GetDefaultRules() []*DiscoverRule {
	return DefaultRules
}
